#coding=utf8
import pickle

import gevent
import gevent.queue
import abu.rpc
import umysql
import gevent.monkey
gevent.monkey.patch_socket()

from proto.db import db_pb2 as db


class DBService(db.DBService):
	def __init__(self,host,port,user,pwd,db,count):
		self.db_conns = gevent.queue.Queue()
		for i in xrange(count):
			conn = umysql.Connection()
			conn.connect(host,port,user,pwd,db)
			self.db_conns.put(conn)

	def close(self):
		pass

	@abu.rpc.ret
	def Query(self,controller,req):
		print req.sql
		conn = self.db_conns.get()
		rs = conn.query(req.sql)
		self.db_conns.put(conn)
		ret = None
		if type(rs) == umysql.ResultSet:
			ret = [[i[0] for i in rs.fields],rs.rows]
		else:
			ret = rs
		resp = db.DBQueryResp()
		resp.ret = pickle.dumps(ret)
		return resp

service = DBService('192.168.10.180',3306,'baozi','baozi','csgs_btt',10)
handler = abu.rpc.Handler(abu.rpc.Transport,service)
server = gevent.server.StreamServer(('',10087),handler)
app = abu.rpc.Application(server)
print 'db server serving...'
app.run()
print 'db server close'
